package com.example.demo.controller;

import com.example.demo.common.Result;
import com.example.demo.model.Organization;
import com.example.demo.service.OrganizationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * 组织架构控制器
 */
@RestController
@RequestMapping("/organizations")
public class OrganizationController {

    @Autowired
    private OrganizationService organizationService;

    @GetMapping("/{id}")
    public Result<List<Organization>> findById(@PathVariable("id") Integer orgId) {
        Organization org = organizationService.findById(orgId);
        List<Organization> result = new java.util.ArrayList<>();
        if (org != null) {
            result.add(org);
        }
        return Result.success(result);
    }

    @GetMapping("/parent/{parentId}")
    public Result<List<Organization>> findByParentId(@PathVariable("parentId") Integer parentId) {
        return Result.success(organizationService.findByParentId(parentId));
    }

    @GetMapping("/type/{type}")
    public Result<List<Organization>> findByType(@PathVariable("type") String orgType) {
        return Result.success(organizationService.findByType(orgType));
    }

    @GetMapping("/parent/{parentId}/type/{type}")
    public Result<List<Organization>> findByParentIdAndType(
            @PathVariable("parentId") Integer parentId,
            @PathVariable("type") String orgType) {
        return Result.success(organizationService.findByParentIdAndType(parentId, orgType));
    }

    @PostMapping
    public Result<Organization> create(@RequestBody Organization organization) {
        return Result.success(organizationService.create(organization));
    }

    @PutMapping
    public Result<Organization> update(@RequestBody Organization organization) {
        return Result.success(organizationService.update(organization));
    }

    @DeleteMapping("/{id}")
    public Result<Boolean> delete(@PathVariable("id") Integer orgId) {
        return Result.success(organizationService.deleteById(orgId));
    }

    @GetMapping
    public Result<List<Organization>> findAll() {
        return Result.success(organizationService.findAll());
    }

    @GetMapping("/{id}/hierarchy")
    public Result<Map<String, Organization>> getOrganizationHierarchy(@PathVariable("id") Integer orgId) {
        return Result.success(organizationService.getOrganizationHierarchy(orgId));
    }

    @GetMapping("/{id}/structure")
    public Result<List<Organization>> getOrganizationStructure(@PathVariable("id") Integer orgId) {
        return Result.success(organizationService.getOrganizationStructure(orgId));
    }

    @GetMapping("/{id}/children")
    public Result<List<Organization>> getChildren(@PathVariable("id") Integer orgId) {
        return Result.success(organizationService.findByParentId(orgId));
    }
} 